package org.jash.shop2201.shop

import android.graphics.Paint
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.snackbar.BaseTransientBottomBar.BaseCallback
import com.google.android.material.snackbar.Snackbar
import org.jash.shop2201.BR
import org.jash.shop2201.R
import org.jash.shop2201.databinding.FragmentCartBinding
import org.jash.shop2201.entity.Cart
import org.jash.shop2201.entity.CartItem
import org.jash.shop2201.mvvm.BaseFragment
import org.jash.shop2201.utils.CommonAdapter
import org.jash.shop2201.utils.Event
import org.jash.shop2201.utils.MyItemAnimator
import org.jash.shop2201.utils.bus


@Route(path = "/shop/cart")
class CartFragment : BaseFragment<FragmentCartBinding, CartViewModel>() {
    val cart by lazy { Cart() }
    val adapter by lazy { CommonAdapter<CartItem>({R.layout.item_cart to BR.cart}, cart.data) }
    override fun initData() {
        viewModel.cartsLiveData.observe(viewLifecycleOwner) {
            adapter += it
            bus.postValue("购物车数量" to it.size)
        }
        viewModel.loadCarts()
    }

    override fun initView() {
        binding.cart = cart
        binding.recycler.adapter = adapter
        binding.recycler.itemAnimator = MyItemAnimator()
        binding.price.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or binding.price.paint.flags
        binding.buy.setOnClickListener {
            ARouter.getInstance().build("/shop/pay")
                .withFloat("total", cart.coupon)
                .withString("body", cart.data.filter(CartItem::checked).joinToString("\n") { "${it.goods_desc} x ${it.count}" })
                .navigation()
        }
    }
    @Event("更新购物车")
    fun updateCart(s:String){
        cart.notifyPropertyChanged(BR.all)
    }
    @Event("删除购物车")
    fun deleteCart(cartItem: CartItem) {
        val position = adapter.removeIf { it.id == cartItem.id }
        Snackbar.make(binding.coordinator, "删除了 ${cartItem.goods_desc}", Snackbar.LENGTH_LONG)
            .setAction("撤销"){}
            .addCallback(object : BaseCallback<Snackbar>() {
                override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                    if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {
                        adapter.add(position, cartItem)
                    } else {
                        viewModel.deleteCart(cartItem.id)
                        cart.notifyPropertyChanged(BR.all)
                    }
                }
            })
            .show()
    }

}